<template>
  <div>
    <el-table :data="roleTable" ref="table" :header-cell-style="{'text-align':'center'}"
              :cell-style="{'text-align':'center'}">
      <el-table-column prop="id" label="id" width="100"/>
      <el-table-column prop="name" label="角色名" width="100"/>
      <el-table-column prop="description" label="角色描述" width="200"/>
      <el-table-column prop="created" label="角色创建时间" width="125"/>
      <el-table-column prop="updated" label="角色修改时间" width="125"/>
      <el-table-column prop="sort" label="角色序号" width="80"/>
      <el-table-column width="300">
        <template slot="header">
          <span>权限</span>
          <el-tooltip placement="top">
            <div slot="content">
              <p>出现“<span class="el-icon-circle-plus"/>”时代表该管理员同为多个角色</p>
            </div>
            <span style="color: black" class="el-icon-question"></span>
          </el-tooltip>
        </template>
        <template slot-scope="scope">
          <span v-if="scope.row.permission.length<=1">{{ scope.row.permission[0].name }}（{{
              scope.row.permission[0].value
            }}）</span>
          <el-tooltip v-else placement="left">
            <div slot="content">
              <p v-for="permission in scope.row.permission">{{ permission.name }}（{{ permission.value }}）</p>
            </div>
            <span>{{ scope.row.permission[0].name }}（{{ scope.row.permission[0].value }}） <span class="el-icon-circle-plus"/></span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template slot-scope="scope">
          <el-button style="margin-right: 10px" type="primary" icon="el-icon-search" @click="openDraw(scope.row)">修改
          </el-button>
          <el-popover width="250" placement="right" :ref="'deleteBy'+scope.row.id">
            <!--在ref利用本名加id的形式生成唯一识别名，以便正确进行“关闭”操作-->
            <p style="text-align: center">确认删除：{{ scope.row.name }}？</p>
            <p style="text-align: center">(将滑动条移至右侧以解锁“确认”)</p>
            <el-slider style="width: 100px;margin: 0 auto" v-model="deleteLine" @change="maxLine($event)"
                       :show-tooltip="false"/>
            <div style="text-align: center">
              <el-button :disabled="confirmDelete" type="danger" @click="deleteManager(scope.row.id)">确认删除</el-button>
            </div>
            <el-button :disabled="scope.row.name === '超级管理员'" slot="reference" type="danger" icon="el-icon-delete" @click="initializeDelete">删除</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>

    <el-drawer :visible.sync="drawer" :title="'正在修改：'+editForm.name1" ref="update">
      <el-form :model="editForm" :rules="rules" ref="updateForm">
        <el-form-item label="角色名" prop="name" label-width="80px">
          <el-input v-model="editForm.name" autocomplete="off" :disabled="updateName"/>
        </el-form-item>
        <el-form-item label="角色描述" prop="description" label-width="80px">
          <el-input v-model="editForm.description" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="角色序号" prop="sort" label-width="80px">
          <el-input v-model="editForm.sort" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="权限" label-width="80px">
          <el-select v-model="editForm.permissionIds" multiple collapse-tags placeholder="请选择" @change="$forceUpdate()">
            <el-option v-for="item in permissionTable" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <div style="text-align: center">
          <el-button type="primary" style="margin-right: 150px" @click="updateConfirm">修改</el-button>
          <el-button type="danger" @click="closingDrawer">取消</el-button>
        </div>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
export default {
  name: "roleList",
  data() {
    return {
      updateName: false,
      roleTable: [],
      drawer: false,
      editForm: {
        id: "",
        name: "",
        description: "",
        sort: "",
        permissionIds: []
      },
      rules: {
        id: [],
        name: [
          {required: true, message: "用户名为空", trigger: "blur"},
          {validator: this.checkName, trigger: "blur"},
        ],
        description: [],
        sort: [
          {required: true, message: "序号为空", trigger: "blur"},
        ],
        permissionIds: [
          {required: true, message: "权限为空", trigger: "blur"},
        ]
      },
      deleteLine: 0,
      confirmDelete: true,
      permissionTable: []
    }
  },
  methods: {
    checkName(rule,value,callback){
      if (value === '超级管理员') {
        callback(new Error('用户名不能为\"超级管理员\"'));
      } else {
        callback();
      }
    },
    openDraw(data) {
      this.editForm.permissionIds.splice(0);
      this.editForm.id = data.id;
      this.editForm.name = data.name;
      this.editForm.description = data.description;
      this.editForm.sort = data.sort;
      if (data.name === "超级管理员") {
        this.updateName = true;
      } else {
        this.updateName = false;
        this.editForm.name1 = data.name
      }
      for (let a = 0; a < data.permission.length; a++) {
        this.editForm.permissionIds.push(data.permission[a].id)
      }
      this.drawer = true;
    },/*打开修改侧边栏*/
    updateConfirm() {
      this.$refs.updateForm.validate((valid) => {
        if (valid) {
          let url = "http://localhost:9999/zx-ams/role/update"
          let data = this.qs.stringify(this.editForm)
          this.axios.create(
              {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
          ).post(url, data).then((response) => {
            if (response.data.state === 200) {
              this.$message({message: "修改完毕，正在刷新页面", type: "success"})
              this.loadRole();
            } else {
              this.$message({message: response.data.message, type: "error"})
            }
          })
          this.closingDrawer();
        }
      })
    },/*确认修改窗口内容并触发closingDrawer*/
    closingDrawer() {
      this.drawer = false;
    },/*关闭修改侧边栏*/
    initializeDelete() {
      this.deleteLine = 0;
      this.confirmDelete = true;
    },/*在打开popover删除窗口时初始化删除界面数据*/
    maxLine(index) {
      if (index !== 100) {
        this.deleteLine = 0;
      }
      this.confirmDelete = index !== 100;
    },/*检查删除确认条是否拉到右侧*/
    deleteManager(id) {
      let url = "http://localhost:9999/zx-ams/role/delete";
      let data = this.qs.stringify({"id": id});
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).post(url, data).then((response) => {
        if (response.data.state === 200) {
          this.$message({message: "删除完毕，正在刷新页面", type: "success"})
          this.loadRole();
          this.$refs[`deleteBy` + id].doClose();
        } else {
          this.$message({message: response.data.message, type: "error"})
        }

      });
    },/*根据id执行删除并关闭对应的popover删除窗口，注意，doClose方法为element官方未写入的关闭popover方法*/
    loadRole() {
      let url = "http://localhost:9999/zx-ams/role/list"
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 200) {
          this.roleTable = jsonResult.data;
          for (let a = 0; a < this.roleTable.length; a++) {
            if (this.roleTable[a].permissionIdString != null) {
              let permissionId = this.roleTable[a].permissionIdString.split(",")
              let permissionName = this.roleTable[a].permissionNameString.split(",")
              let permissionValue = this.roleTable[a].permissionValueString.split(",")
              let permission = [];
              for (let b = 0; b < permissionId.length; b++) {
                let Array = {"id": parseInt(permissionId[b]), "name": permissionName[b], "value": permissionValue[b]};
                permission.push(Array);
              }
              this.roleTable[a].permission = permission;
            }
          }

        } else {
          this.$alert(jsonResult.message, '错误', {confirmButtonText: '确定'});
        }
      })
    },
    loadPermission() {
      let url = "http://localhost:9999/zx-ams/permission/list"
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).get(url).then((response) => {
        if (response.data.state === 200) {
          this.permissionTable = response.data.data;
        }
      })
    }
  },
  mounted() {
    this.loadRole();
    this.loadPermission();
  }
}
</script>

<style scoped>

</style>